from models.models import UserRoleLink
from service.BaseService import BaseService
from config import settings
from sqlmodel import Session, select
from typing import Optional

class UserRoleService(BaseService[UserRoleLink]):
    def __init__(self):
        super().__init__(UserRoleLink)

    def assign_role_to_user(self, user_id: str, role_id: str):
        new_user_role = UserRoleLink(user_id=user_id, role_id=role_id, create_by=user_id, update_by=user_id)
        return self.create(new_user_role)

    def get_user_by_role(self, role_id: Optional[int] = None):
        statement = select(UserRoleLink).where(UserRoleLink.role_id == role_id)
        return self.session.exec(statement).all()

    def get_user_role_link(self, user_id: Optional[int] = None):
        statement = select(UserRoleLink).where(UserRoleLink.user_id == user_id)
        return self.session.exec(statement).first()

    def update_user_role_link(self, user_id: str, role_id: str):
        statement = select(UserRoleLink).where(UserRoleLink.user_id == user_id)
        user_role_link = self.session.exec(statement).first()
        user_role_link.role_id = role_id
        self.session.commit()
        return user_role_link


